package top.krwlc.server.util;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * krwlc
 * top.krwlc.server.util
 *
 * @author Lanscarlos
 * @since 2022-04-05 20:11
 */
public class DateUtil {

    /**
     * 从身份证中提取出生日期
     *
     * @param identityCode 身份证号
     * @return 出生日期
     * */
    public static Date extractBirth(String identityCode) throws ParseException {
        String birth = identityCode.subSequence(6, 14).toString();
        return new SimpleDateFormat("yyyyMMdd").parse(birth);
    }

    /**
     * 计算真实年龄
     * */
    public static int calcAge(Date birth) {
        Calendar cal = Calendar.getInstance();
        if (cal.before(birth)) return 0;

        int year = cal.get(Calendar.YEAR);
        int day = cal.get(Calendar.DAY_OF_YEAR);

        cal.setTime(birth);
        int age = year - cal.get(Calendar.YEAR);

        if (day < cal.get(Calendar.DAY_OF_YEAR)) {
            // 当年未过生日
            return age - 1;
        } else {
            return age;
        }
    }

}
